package com.wf.it.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.*;

public class JwtUtil {
    public static String createToken(String secretKey, int expSecond, String subject, Map<String,Object> map){
        JwtBuilder builder= Jwts.builder();//创建一个jwt生成器
        builder.setId(UUID.randomUUID().toString());//生成随机数作为这个jwt凭证的主标记
        builder.setIssuedAt(new Date());//jwt的生产日期
        builder.signWith(SignatureAlgorithm.HS256,secretKey);//加密算法
        builder.setClaims(map);//设置额外携带的值(用户信息)
        builder.setSubject(subject);//设置主键(用户信息的id)
        builder.setExpiration(new Date(System.currentTimeMillis()+expSecond*1000));//jwt的过期时间
        String s=builder.compact();//创建jwt字符串(凭证
        System.out.println(s);
        return s;
    }
    //解析还原jwt里面的信息
    public static Claims parseToken(String secretKey, String jwtStr){
       Claims claims= Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtStr).getBody();
       return claims;
    }
    public static  void main(String[] args) throws InterruptedException {
        Map<String,Object> map=new HashMap<>();
        map.put("name","zhangsan");
        map.put("nickname","张三");
        String token=createToken("11112222",3600,1+"",map);
        String[] ss=token.split("\\.");
        System.out.println(new String(Base64.getDecoder().decode(ss[0])));
        System.out.println(new String(Base64.getDecoder().decode(ss[1])));


        System.out.println("------解析-------");
        token="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwibmFtZSI6InpoYW5nc8FuIiwibmlja25hbWUiOiLlvKDkuIkiLCJleHAiOjE2OTgyMDU0ODN9.0hR47xTbdfEFwzWNT7usCJMIFbfhZmvF-ybTMnQaH6Q";
        Claims claims=parseToken("11112222",token);
        System.out.println("主标识:"+claims.getSubject());
        System.out.println("用户名"+claims.get("name"));
        System.out.println("昵称"+claims.get("nickname"));
    }
}
